﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace StringToDictionary
{
    static public class CStringToDictionary
    {
        public static IDictionary<string, string> ToDictionary(this string s )
        {
            var result = new Dictionary<string, string>();
            if ( s == null )
            {
                return result;
            }

            if ( s.Length == 0 )
            {
                return result;
            }
            var pairs = s.Split(';');

            foreach( string pair in pairs )
            {
                if ( pair.Length == 0 )
                {
                    throw new ArgumentException("Syntax error. Check semicolons <;> separate input string into nonempty substrings.");
                }
                else
                {
                    var keyAndValue = pair.Split('=');
                    if ( keyAndValue.Length != 2 )
                    {
                        throw new ArgumentException("Syntax error. Check one single equals <=> character separates each into key/value pairs.");
                    }
                    else
                    {
                        if ( keyAndValue[0].Length == 0 )
                        {
                            throw new ArgumentException("Syntax error. Key must not be empty.");                                                     
                        }
                        if (keyAndValue[1].Length == 0)
                        {
                            throw new ArgumentException("Syntax error. Value must not be empty.");
                        }

                        if ( result.ContainsKey( keyAndValue[0]) )
                        {
                            throw new ArgumentException("Syntax error. Check all keys are unique.");                            
                        }
                        else
                        {
                            result[keyAndValue[0]] = keyAndValue[1];                            
                        }
                    }

                }               
            }

            return result;


            return s.Split(';')
                .Select(t => t.Split('='))
                .Where(pair => pair.Length == 2)
                .ToDictionary(pair => pair[0], pair => pair[1]);

        }
    }
}
